package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
   // private List<PrintWriter> allOut = new ArrayList<>();
    private Map<String,PrintWriter> allOut = new HashMap<>();
    /**
     * java.net.ServerSocket
     * 运行在服务器端，主要作用两个
     * 1.
     * 2.监听端口，一旦有客户端连接，创建Socket对象，与客户端通信
     */
    private ServerSocket serverSocket;
    private ExecutorService threadPool = Executors.newFixedThreadPool(50);
    public Server() {
        try {

            /**
             * 创建ServerSocket对象，会申请一个端口
             *
             */
            System.out.println("正在启动服务器");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户连接了");
                Runnable handler = new ClientHandler(socket);
                threadPool.execute(handler);
            }
            } catch(IOException e){
                e.printStackTrace();
            }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable {
        private String nickname;
        private Socket socket;
        private String host;
        public ClientHandler(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        @Override
        public void run() {
            PrintWriter pw =null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                nickname = br.readLine();

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter psw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(psw);
                pw = new PrintWriter(bw, true);

                synchronized (allOut) {
                    //allOut.add(pw);
                    allOut.put(nickname,pw);
                }
                broadcast(nickname+"["+host + "]上线了,当前人数:" + allOut.size());
                String message;

                while ((message = br.readLine()) != null) {
                    if(message.startsWith("@")){
                        br(message);
                    }else {
                        broadcast(nickname + "[" + host + "]说:" + message, pw);
                        saveMessage(nickname,null,message);
                    }
                }
            } catch (IOException e) {
            } finally {
                synchronized (allOut) {
                    //allOut.remove(pw);
                    allOut.remove(nickname);
                }
                broadcast(nickname+"["+host + "]下线了,当前人数:" + allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        private void broadcast(String message){
            System.out.println(message);
            synchronized (allOut) {
//                for (PrintWriter o : allOut){
//                    o.println(message);
//                }
                for (PrintWriter o : allOut.values()){
                    o.println(message);
                }
            }
        }
        private void broadcast(String message, PrintWriter pw){
            System.out.println(message);
            synchronized (allOut) {
//                for (PrintWriter o : allOut){
//                    if (o.equals(pw)){
//                        continue;
//                    }
//                    o.println(message);
//                }
                for (PrintWriter o : allOut.values()){
                    if (o.equals(pw)){
                        continue;
                    }
                    o.println(message);
                }
            }
        }
        private void br(String message){
            if (message.matches("@.+:.+")) {
                String toNickName = message.substring(1, message.indexOf(":"));
                if (allOut.containsKey(toNickName)) {
                    PrintWriter pw = allOut.get(toNickName);
                    String toMessage = message.substring(message.indexOf(":") + 1);
                    pw.println(nickname + "[" + host + "]:" + toMessage);
                    saveMessage(nickname,toMessage,toMessage);
                }else{
                    PrintWriter pw = allOut.get(nickname);
                    pw.println("该用户不存在");
                }
            }else {
                PrintWriter pw = allOut.get(nickname);
                pw.println("私聊格式不正确，格式应当为@对方昵称:私有信息");
            }
        }
        private void saveMessage(String fromUser,String toUser,String message){
            try(
                    Connection conn = DBUtil.getConnection()
            ) {
                String sql = "INSERT INTO charinfo (from_user,to_user,content) VALUES (?,?,?)";
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setString(1,fromUser);
                ps.setString(2,toUser);
                ps.setString(3,message);
                ps.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
